﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace Biotech.Common.Util
{

    public class XmlUtil
    {
        /// <summary>
        /// 将XML文件反序列化成对象
        /// </summary>
        /// <typeparam name="T">返回的对象类型</typeparam>
        /// <typeparam name="xml">文件路径</typeparam>
        /// <typeparam name="xmlRootName">xml根节点</typeparam>
        /// <returns>返回对象类型</returns>
        public static T DeserializeFile<T>(string filePath, string xmlRootName = "Root")
        {
            T result = default(T);
            if (File.Exists(filePath))
            {
                using (StreamReader reader = new StreamReader(filePath))
                {
                    XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
                        new XmlSerializer(typeof(T)) : new XmlSerializer(typeof(T), new XmlRootAttribute(xmlRootName));
                    result = (T)xmlSerializer.Deserialize(reader);
                }
            }

            return result;
        }

        /// <summary>
        /// 将对象序列化成XML文件
        /// </summary>
        /// <typeparam name="filePath">xml文件路径</typeparam>
        /// <typeparam name="sourceObj">数据对象</typeparam>
        /// <typeparam name="xmlRootName">xml根节点</typeparam>
        public static void SerializerFile(string filePath, object sourceObj, string xmlRootName = "Root")
        {
            if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
            {
                Type type = sourceObj.GetType();
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
                        new XmlSerializer(type) : new XmlSerializer(type, new XmlRootAttribute(xmlRootName));

                    xmlSerializer.Serialize(writer, sourceObj);
                }
            }
        }

        
    }   
}
